package com.yz.minded.aspect;

import com.yz.minded.contant.UserConstant;
import com.yz.minded.pojo.User;
import com.yz.minded.service.UserService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class UpdateLoginUserAspect {

    public static HttpServletRequest request = null;

    @Resource
    private UserService userService;

    @After("controllerMethods()")
    public void updateLoginUser(JoinPoint joinPoint) {
        request = (HttpServletRequest) joinPoint.getArgs()[1];
        // 获取用户登录态
        User loginUser = (User) request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if (loginUser != null) {
            long loginUserId = loginUser.getId();
            // 从数据库中获取数据同步
            User user = userService.getById(loginUserId);
            // 用户信息脱敏
            User safetyUser = userService.getSafetyUser(user);
            // 同步到 Session
            request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, safetyUser);
            // TODO 考虑当有用户信息发生改变时，删除缓存中主页的内容，重新更新主页内容
        }
    }

    /**
     * 切点表达式
     * 拦截用户所有的修改信息方法
     */
    @Pointcut("execution(* com.yz.minded.controller.UserController.userLogin(..))" +
            "|| execution(* com.yz.minded.controller.UserController.updateUser(..))" +
            "|| execution(* com.yz.minded.controller.UserTagController.updateTags(..))" +
            "|| execution(* com.yz.minded.controller.UserController.upload(..))")
    public void controllerMethods(){}

}
